%
% Created 11/01/12 Vasyl Mykhalchuk
%
function [resultCriticalPoints] = extractFPs(sField, adjVerticesList, distMatrix, epsilon, kTRESHOLD)

% maximum number of critical points NB substitute this hard-coded element
% with dynamic array
sizeN = size(sField);
kMaxCriticalPoints = sizeN(1);
criticalPointsTmp = zeros(kMaxCriticalPoints,1,'int32');
numberOfVertices = sizeN;

% the current number of feature/critical points found 
currentNumberOfCriticalPoints = 0;

for iVertex = 1:numberOfVertices
    adjVerticesList = neighborhoodOfVertex(iVertex, distMatrix, epsilon);
    if ( isCriticalPoint(iVertex, sField, adjVerticesList, kTRESHOLD) )
        %h = chi2test( (sField(adjVerticesList))', 0.2);
        h = 1;
        if ( h )
        if (currentNumberOfCriticalPoints == 0) currentNumberOfCriticalPoints = 1; end
            criticalPointsTmp( currentNumberOfCriticalPoints ) = int32(iVertex);
            currentNumberOfCriticalPoints = currentNumberOfCriticalPoints + 1;
        end % if
   end
end

if(currentNumberOfCriticalPoints~=0)
    resultCriticalPoints = zeros(currentNumberOfCriticalPoints - 1,1, 'int32');
else
    resultCriticalPoints = 0;
end;%if

for i = 1:currentNumberOfCriticalPoints - 1
    resultCriticalPoints(i) = criticalPointsTmp(i);
end

resultCriticalPoints = resultCriticalPoints';

end

function [ isCriticalPoint ] = isCriticalPoint( iVertex, scalarField, adjacentVertices, kTRESHOLD )
isCriticalPoint = 0;

% adjacentVertices = adjVerticesList(iVertex,:);
[x, length] = size(adjacentVertices);

fpValues = zeros(length, 1);
for i = 1:length
    if (adjacentVertices(i) ~= 0)
    fpValues(i) = abs( scalarField( adjacentVertices(i) ) );
    end % if
end % for

maxFPVal = max(fpValues);

if ( abs(scalarField(iVertex)) > maxFPVal  )
    isCriticalPoint = 1;    
end % if

if ( abs(scalarField(iVertex)) <= kTRESHOLD )
    isCriticalPoint = 0;
end

end % function

%{
% ========================================================================
function [isCriticalPoint] = isCriticalPoint(iVertex, scalarField, adjVerticesList)
kTreshHold = 0.0000001;
isCriticalPoint = 0;
adjacentVertices = adjVerticesList(iVertex,:);
[x, length] = size(adjacentVertices);
i = 1;
if( scalarField(iVertex) >= 0)
while (i<length)
    if (adjacentVertices(i) ~= 0)
        if ( scalarField(iVertex) <= scalarField(adjacentVertices(i)) )
            i = length + 1;
        end%if inner
    end%if outer
    i = i + 1;
end%while
else
    while (i<length)
    if (adjacentVertices(i) ~= 0)
        if ( scalarField(iVertex) >= scalarField(adjacentVertices(i)) )
            i = length + 1;
        end%if inner
    end%if outer
    i = i + 1;
end%while
    
end%if
if ( (i == length) && (abs(scalarField(iVertex)) > kTreshHold)  )
    isCriticalPoint = 1;
end%if


end%function isCriticalPoint
%}